package cn.tedu.apps_system.service.impl;

import cn.tedu.apps_system.base.response.ResultCode;
import cn.tedu.apps_system.exception.BusinessException;
import cn.tedu.apps_system.mapper.MerchantMapper;
import cn.tedu.apps_system.mapper.OrderItemMapper;
import cn.tedu.apps_system.mapper.OrderMapper;
import cn.tedu.apps_system.pojo.entity.Order;
import cn.tedu.apps_system.pojo.entity.OrderItem;
import cn.tedu.apps_system.pojo.vo.ProductSalesVO;
import cn.tedu.apps_system.pojo.vo.SalesStatisticsVO;
import cn.tedu.apps_system.service.StatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public SalesStatisticsVO getSalesStatistics(Long merchantId) {
        // 检查商家是否存在
        if (merchantMapper.selectById(merchantId) == null) {
            throw new BusinessException(ResultCode.MERCHANT_NOT_EXIST);
        }

        SalesStatisticsVO statisticsVO = new SalesStatisticsVO();

        // 获取商家所有已完成订单
        List<Order> orders = orderMapper.selectByMerchantIdAndStatus(merchantId, 3); // 3表示已完成订单

        int totalSales = 0;
        double totalAmount = 0.0;
        Map<Long, ProductSalesVO> productSalesMap = new HashMap<>();

        for (Order order : orders) {
            totalAmount += order.getActualAmount();

            // 获取订单项
            List<OrderItem> orderItems = orderItemMapper.selectByOrderId(order.getId());
            for (OrderItem item : orderItems) {
                totalSales += item.getQuantity();

                ProductSalesVO productSales = productSalesMap.getOrDefault(item.getProductId(), new ProductSalesVO());
                productSales.setProductId(item.getProductId());
                productSales.setProductName(item.getProductName());
                productSales.setSales(productSales.getSales() + item.getQuantity());
                productSales.setAmount(productSales.getAmount() + item.getTotalPrice());

                productSalesMap.put(item.getProductId(), productSales);
            }
        }

        statisticsVO.setTotalSales(totalSales);
        statisticsVO.setTotalAmount(totalAmount);
        statisticsVO.setProductSales(new ArrayList<>(productSalesMap.values()));

        return statisticsVO;
    }
}